package com.example.snakegame.utils

import android.content.Context
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.example.snakegame.model.Score
import com.example.snakegame.model.User

class SharedPreferencesManager(context: Context) {
    companion object {
        private const val TAG = "SharedPrefsManager"
    }

    private val prefs = context.getSharedPreferences("snake_game_prefs", Context.MODE_PRIVATE)
    private val gson = Gson()

    fun saveUser(user: User) {
        prefs.edit().putString("user_${user.username}", gson.toJson(user)).apply()
    }

    fun getUser(username: String): User? {
        val userJson = prefs.getString("user_${username}", null)
        return userJson?.let { gson.fromJson(it, User::class.java) }
    }

    fun saveScore(score: Score) {
        try {
            val scores = getScores().toMutableList()
            scores.add(score)
            scores.sortByDescending { it.score }
            prefs.edit().putString("scores", gson.toJson(scores)).apply()
            Log.d(TAG, "Score saved successfully: $score")
        } catch (e: Exception) {
            Log.e(TAG, "Error saving score", e)
        }
    }

    fun getScores(): List<Score> {
        return try {
            val scoresJson = prefs.getString("scores", "[]")
            val type = object : TypeToken<List<Score>>() {}.type
            gson.fromJson<List<Score>>(scoresJson, type).also {
                Log.d(TAG, "Retrieved ${it.size} scores")
            }
        } catch (e: Exception) {
            Log.e(TAG, "Error getting scores", e)
            emptyList()
        }
    }
} 